package org.nulldevice.tankshot.swing;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;

import org.nulldevice.tankshot.*;
import org.nulldevice.tankshot.entities.Item;

public class GameCanvas extends Canvas implements Runnable {
	
	private JFrame gameWindow;
	/** The strategy that allows us to use accelerate page flipping */
	private BufferStrategy strategy;
	private boolean doExit = false;

	public GameCanvas(Game g) {
		
		gameWindow = new JFrame("Tanks");
		final JPanel panel = (JPanel) gameWindow.getContentPane();

		panel.setPreferredSize(new Dimension(800, 600));
		panel.setLayout(null);

		// setup our canvas size and put it into the content of the frame
		setBounds(0, 0, 800, 600);
		panel.add(this);

		// Tell AWT not to bother repainting our canvas since we're
		// going to do that our self in accelerated mode
		setIgnoreRepaint(true);

		// finally make the window visible
		gameWindow.pack();
		gameWindow.setResizable(false);
		gameWindow.setVisible(true);

		// add a key input system (defined below) to our canvas
		// so we can respond to key pressed
		addKeyListener(new GameKeyListener(g));
		addMouseListener(new GameMouseListener(g));
		addMouseMotionListener(new GameMouseListener(g));
		gameWindow.addWindowListener(new GameWindowListener(g));

		// request the focus so key events come to us
		requestFocus();

		// create the buffering strategy which will allow AWT
		// to manage our accelerated graphics
		createBufferStrategy(2);
		strategy = getBufferStrategy();
	}
	
	public void run() {
		GameContainer container = GameContainer.getInstance();
		
		while(!doExit) {
			// Get hold of a graphics context for the accelerated
			// surface and blank it out
			Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
			g.setColor(Color.white);
			g.fillRect(0, 0, 800, 600);
			
			for (final ArrayList<? extends Item> list : container.getItems()) {
				for (int i = 0; i < list.size(); i++) {
					final Item item = list.get(i);
					item.draw(g);
				}
			}
			// finally, we've completed drawing so clear up the graphics
			// and flip the buffer over
			g.dispose();
			strategy.show();
		}
	}
	
	public void stop() {
		doExit = true;
	}

}
